/**
 * JungoPushModule
 * Peeker.java
 * 
 * Copyright 2013 Teachizen
 * Written by cloudstick
 *	2013. 8. 12. first written.
 *
 * note:
 */
package com.jungo.module.scheduler;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.jungo.module.bean.Job;
import com.jungo.module.service.PushService;

/**
 * @author cloudstick
 *
 */
@Slf4j
public class Peeker extends QuartzJobBean {
	private static final String APPLICATION_CONTEXT_KEY = "applicationContext";
	private static final String JOB_BEAN_NAME_KEY = "job.bean.name";
	
	@Override
	protected void executeInternal(final JobExecutionContext jobExecutionContext)
			throws JobExecutionException {
		// TODO Auto-generated method stub
		
		try {
			//스프링 컨텍스트와 쿼츠가 다른 컨텍스트에서 구동되어 서비스 빈을 쿼츠 컨텍스트로 불러온다.
			final SchedulerContext schedulerContext = jobExecutionContext.getScheduler().getContext();
			final ApplicationContext applicationContext = (ApplicationContext)schedulerContext.get(APPLICATION_CONTEXT_KEY);
			final String jobBeanName = (String)jobExecutionContext.getJobDetail().getJobDataMap().get(JOB_BEAN_NAME_KEY);
			final PushService pushService = (PushService)applicationContext.getBean(jobBeanName);
			
			final List<Job> jobs = pushService.getJob();
			if ( jobs == null || jobs.isEmpty() ) {
				return;
			}
			pushService.doPush(jobs);
			
		} catch(Exception e) {
			log.error("Exception occured.", e);
		}
	}
}
